package Model.Languages;

import Model.BusinessRule;

public class Oracle extends Template{

	private BusinessRule b;
	
	public Oracle(){
		super();
	}

	
	
	public String Generate(BusinessRule bu){
		b = bu;

		String text = "";
		
		// CREATE OR REPLACE TRIGGER "TRIGGERNAAM"
		// "BEFORE | AFTER" "UPDATE|INSERT|DELETE (OR)"
		// OF (COLUMNTRIGGER) ON (TABLETRIGGER)
		// BEGIN
		
		
		//text += "CREATE OR REPLACE TRIGGER BRG_TR_" + b.getTable() + "_" + b.getColumn() + "\n";
		text += "CREATE OR REPLACE TRIGGER BRG_TR_" + createNameConvention(b.getTable(), b.getColumn(), b.getBusinessRuleID()) + "\n";
		text += "  " + b.getTriggerWhen() + " ";
		
		for(int i = 0; i < b.getTriggerActions().length; i++){
			
			if(i != 0 && i != b.getTriggerActions().length){
				text += " OR ";
			}
			
			text += b.getTriggerActions()[i];
		}
		
		text += " OF " + b.getColumn() + " ON " + b.getTable() + "\n";
		
		text += "FOR EACH ROW\n";
		
		//Begin Pl/SQL
		text += "BEGIN\n";
		
		text += "IF ";
		
//		if(this.iruleTypes.getConstrainCount() != 1){
//			for(int i = 0; i < this.iruleTypes.getConstrainCount(); i++){
//				if(i != 0 && i != this.iruleTypes.getConstrainCount()){
//					text += " AND ";
//				}
//				text += b.getConstrains()[i];
//			}
//		}
		
		text += createCondition();
		
		text += " THEN\n";
//		text += "  \n";
//		text += "ELSE\n";
		text += "  Raise_Application_Error(-20000, \'"+ b.getErrorMessage() +"\');\n";
		text += "END IF;\n";
		text += "END;\n";
		
		return text;
		
	}
	
	private String createCondition(){
		String text = "";
		String[] parsedOperation = this.iruleTypes.parseOperation(b.getOperator());
		
		for(int concount = 0; concount < parsedOperation.length; concount++){
			
			if(concount != 0 && concount != parsedOperation.length){
				text += " OR";
			}
			
			//text += " " + b.getTable() + "." + b.getColumn() + " ";
			text += " :new." + b.getColumn() + " ";
			text += parsedOperation[concount] + " ";
			text += b.getConstrains().get(concount).giveConstraint();
		}
		
		return text;
	}
	
	private String createNameConvention(String t, String c, int id){
		String text = "";
		
		text += t.substring(0, 4);
		
		text += "_";
		
		text += c.substring(0, 4);
		
		text += "_";
		
		text += id;
		
		return text.toUpperCase();
	}
	
	
}
